<?php

// 1. 加载数据库配置
$config = [
    'DB_HOST' => 'localhost',
    'DB_USER' => 'root',
    'DB_PASSWORD' => '123465',
    'DB_NAME' => 'wp',
    'TABLE_PREFIX' => 'wp_6_'
];

// 2. 连接数据库
$db = new mysqli($config['DB_HOST'], $config['DB_USER'], $config['DB_PASSWORD'], $config['DB_NAME']);
if ($db->connect_error) {
    die("数据库连接失败: " . $db->connect_error);
}


function sanitize_title($data)
{
   return md5($data);   
}


// 3. 检查标签是否存在，不存在则创建
function ensure_tag_exists($db, $prefix, $tag_name)
{
    $slug = md5($tag_name);
    // 检查标签是否已存在
    $query = $db->prepare("
        SELECT term_id 
        FROM {$prefix}terms 
        WHERE slug = ?
    ");
    $query->bind_param('s', $slug);
    $query->execute();
    $result = $query->get_result();

    if ($result->num_rows > 0) {
        return $result->fetch_row()[0]; // 返回已存在的标签ID
    }

    // 创建新标签
    $db->query("INSERT INTO {$prefix}terms (name, slug) VALUES ('$tag_name', '" . $slug . "')");
    $term_id = $db->insert_id;

    // 插入到分类法表
    $db->query("
        INSERT INTO {$prefix}term_taxonomy (term_id, taxonomy, description) 
        VALUES ($term_id, 'post_tag', '')
    ");

    return $term_id;
}

//读取1.txt里面的的标签，每个标签占一行，将这些标签插入到wordpress的post_tag表中

$file = fopen(__DIR__ . '/1.txt', 'r');
if ($file) {
    while (($tag_name = fgets($file)) !== false) {
        $tag_name = trim($tag_name);
        if (!empty($tag_name)) {
            ensure_tag_exists($db, $config['TABLE_PREFIX'], $tag_name);
        }
    }
    fclose($file);
}

$db->close();
echo "标签插入完成\n";
